import { menuStoreType } from '#/menuStore/menuStoreType'
import { store } from '@/store'
import Cookies from 'js-cookie'
import { App } from 'vue'
import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'

const LoginDetails = () => import('@/pages/login/login.vue')
const IndexDetails = () => import('@/pages/index/index.vue')
const HomeDetails = () => import('@/pages/home/home.vue')
const ErrDetails = () => import('@/pages/err/err.vue')

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/index',
  },
  {
    path: '/login',
    name: 'login',
    component: LoginDetails,
  },
  // 404
  {
    path: '/:pathMatch(.*)*',
    component: ErrDetails,
  },
]

const router = createRouter({
  history: createWebHashHistory(),
  routes,
})

// 动态添加路由

const addRouteFlex = () => {
  let menus: menuStoreType[] = store.getters.getNewMenus

  const homeRoute: RouteRecordRaw = {
    path: '/index',
    name: 'index',
    redirect: '/index/home',
    component: IndexDetails,
    children: [
      {
        path: 'home',
        name: 'home',
        component: HomeDetails,
      },
    ],
  }
  router.addRoute(homeRoute)

  for (let index = 0; index < menus.length; index++) {
    const item = menus[index]

    const newRoute: RouteRecordRaw = {
      path: `/${item.topMenu.name}`,
      name: item.topMenu.name,
      redirect: `/${item.topMenu.name}/${item.children[0].name}`,
      component: IndexDetails,
      children: [],
    }

    for (let i = 0; i < item.children.length; i++) {
      const itemChild = item.children[i]

      const newRouteChild: RouteRecordRaw = {
        path: itemChild.name,
        name: itemChild.name,
        component: () =>
          import(`@/pages/${item.topMenu.name}/${itemChild.name}.vue`),
      }

      newRoute.children?.push(newRouteChild)
    }
    router.addRoute(newRoute)
  }
}

router.beforeEach(async (_to, _from, next) => {
  const authorization = Cookies.get('Authorization')

  if (!authorization && _to.path !== '/login') {
    next({ path: '/login' })
    return
  }

  if (authorization && _to.path === '/login') {
    next({ path: '/index' })
    return
  }

  if (authorization && store.state.menus.length === 0) {
    await store.dispatch('getAdminInfo')
    addRouteFlex()
    next(_to.path)
    return
  }

  next()
})

export const initRouter = (app: App<Element>) => {
  app.use(router)
}
